import re
import time
import os
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from configs.other_config import REGEX_FILE_PATH, REGEX_FOLDER_PATH
from instruction.utils import load_json_file


# 预编译正则规则
def precompiled_regex_relus():
    # 存储编译后的规则
    rules = {}

    # 遍历意图和规则
    for intent, intent_rules in regex_rules.items():
        compiled_intent_rules = [re.compile(rule, re.IGNORECASE) for rule in intent_rules]
        rules[intent] = compiled_intent_rules

    return rules


# 读取正则json文件
regex_rules = load_json_file(REGEX_FILE_PATH)
# 预编译正则规则
try:
    compiled_rules = precompiled_regex_relus()
    # 正则json文件是否正常
    regex_json = True
except:
    regex_json = False


class FileEventHandler(FileSystemEventHandler):
    def on_modified(self, event):
        global regex_rules, compiled_rules, regex_json
        if event.src_path == REGEX_FILE_PATH:
            try:
                regex_json = True
                # 读取正则json文件
                regex_rules = load_json_file(REGEX_FILE_PATH)
                # 预编译正则规则
                compiled_rules = precompiled_regex_relus()
                # 文件修改时间
                modification_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                log_message = f"{os.path.basename(REGEX_FILE_PATH)} modified at {modification_time}"
                print(log_message)
            except:
                regex_json = False
                print(f"There is a problem with the {os.path.basename(REGEX_FILE_PATH)} file.")


observer = Observer()
event_handler = FileEventHandler()
observer.schedule(event_handler, REGEX_FOLDER_PATH, True)
observer.start()

# 法律咨询2正则规则
law_regex_rules = [
    re.compile(
        r'.*(你(能|可以)|告诉我|要|我(需要|想要|请求)|发起|开始|进行|帮?我(想|要)(找|咨询一下))?(法律|律师)(咨询|援助|帮助|服务|事务所).*'),
    re.compile(r'.*(告诉我|播报|我需?要|(讲|说|介绍)一(下|个))(律所|律师)(电话|律师事务所).*'),
    re.compile(r'.*(我|你)可以(咨询|回答|问你)法律(相关)?问题吗.*'),
    re.compile(r'.*我要打官司.*')
]


# 法律咨询2
async def law_relu(prompt):
    law_relu.matching_type = "regex"
    try:
        for i in compiled_rules["law"]:
            if re.match(i, prompt):
                return '2'
    except:
        for i in law_regex_rules:
            if re.match(i, prompt):
                return '2'
    return None


# 卡车维修3正则规则
repair_regex_rules = [
    re.compile(r'.*(我的?卡?车(出问题了|坏了)(怎么办？?)?|(你|我)可以(回答|问你)卡车维修的问题吗？?).*'),
    re.compile(r'.*(我((想|需)?要))?维修(卡|汽)车(联系)?(电话)?.*'),
    re.compile(r'.*(卡车)?(维修|售后)(服务|联系)(电话|服务).*'),
    re.compile(r'.*卡车维修.*'),
    re.compile(r'.*保养(卡车|重卡).*'),
    re.compile(r'.*(卡车|重卡)保养.*')
]


# 卡车维修3
async def automobile_maintenance_relu(prompt):
    automobile_maintenance_relu.matching_type = "regex"
    try:
        for i in compiled_rules["repair"]:
            if re.match(i, prompt):
                return '3'
    except:
        for i in repair_regex_rules:
            if re.match(i, prompt):
                return '3'
    return None


# 车祸4正则规则
accident_regex_rules = [
    re.compile(r'.*(出现)?车祸了?(怎么办|找谁)?.*'),
    re.compile(r'.*(撞车|追尾|撞人|(交通|卡车)事故).*'),
    re.compile(r'.*(报警|火警|急救)电话.*')
]


# 车祸4
async def car_accident_relu(prompt):
    car_accident_relu.matching_type = "regex"
    try:
        for i in compiled_rules["accident"]:
            if re.match(i, prompt):
                return '4'
    except:
        for i in accident_regex_rules:
            if re.match(i, prompt):
                return '4'
    return None


# 卡车购买推荐5正则规则
buy_truck_regex_relus = [
    re.compile(r'.*我?(想|要)?(购?买|买一辆)新?(卡车|重卡).*'),
    re.compile(r'.*(我(要|想))?买(新|牵引|载货|自卸|(解放)?卡)车.*'),
    re.compile(r'.*怎么买卡?车.*'),
    re.compile(r'.*(小卡你能给我一些)?卡车(购买)?(电话|推荐|意见|建议)吗?.*'),
    re.compile(r'.*(解放|一汽)(卡车|重卡)购买.*'),
    re.compile(r'.*售车(电话|热线)?.*')
]


# 卡车购买推荐5
async def buy_truck_relu(prompt):
    buy_truck_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["buy_truck"]:
            if re.match(i, prompt):
                return '5'
    except:
        for i in buy_truck_regex_relus:
            if re.match(i, prompt):
                return '5'
    return None


# 打招呼10正则规则
greeting_regex_rules = [
    re.compile(r'.*(小卡)*[，。！？]?(您好|早上好|hello|hi|hey|晚上好|上午好|中午好|下午好)[，。！？]?啊?(小卡)?',
               re.IGNORECASE),
    re.compile(r'^(小卡)*[，。！？]?(你好)[，。！？]?啊?(小卡)?[？，。！]?$', re.IGNORECASE),
]


# 打招呼10
async def greeting_relu(prompt):
    greeting_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["greeting"]:
            if re.match(i, prompt):
                return '10'
    except:
        for i in greeting_regex_rules:
            if re.match(i, prompt):
                return '10'
    return None


# 时间11正则规则
time_regex_rules = [
    re.compile(
        r'^(小卡)*[，。！？]?(((播报|告诉我|讲一下|说一下)?(当前|现在)?.?(什么)?时间(吗|啊|了)?[，。！？]?(小卡)?$)|当前时间|现在是?什么(时候|时间)(了|呢)啊?|现在是?什么(时候|时间)(了|呢)?啊?)[，。！？]?$'),
    re.compile(r'.*(小卡)*[，。！？]?(告诉我|播报|讲一下|说一下)?.*几点钟?了?(吗|啊)?[，。！？]?(小卡)?$'),
    re.compile(r'.*(小卡)*[，。！？]?(告诉我|播报|讲一下|说一下)?.*时辰了?(吗|啊)?[，。！？]?(小卡)?$')
]


# 时间11
async def time_relu(prompt):
    time_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["time"]:
            if re.match(i, prompt):
                return '11'
    except:
        for i in time_regex_rules:
            if re.match(i, prompt):
                return '11'
    return None


# 日期、星期几正则规则
date_regex_relus = [
    re.compile(r'^(小卡)*.?[，。！？]*(今天|现在|今儿?个)?(几月)?(几号了?|(周|星期|礼拜)几)(啊|呢|呀)?[？，。！]?$')
]


async def date_relu(prompt):
    date_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["date"]:
            if re.match(i, prompt):
                return 'date'
    except:
        for i in date_regex_relus:
            if re.match(i, prompt):
                return 'date'
    return None


# 人工服务12正则规则
service_regex_relus = [
    re.compile(r'.*(告诉我|播报|(讲|说)(一下)?|联系)?(人工|客服)(电话|服务|客服)(是多少)?.*')
]


# 人工服务12
async def service_relu(prompt):
    service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["service"]:
            if re.match(i, prompt):
                return '12'
    except:
        for i in service_regex_relus:
            if re.match(i, prompt):
                return '12'
    return None


# 跳舞54正则规则
dance_regex_relus = [
    re.compile(r'.*(展示)?(舞蹈|(跳|来)一?(个|支|段)舞).*'),
    re.compile(r'.*你(能|会)跳舞吗[？，。！]?'),
    re.compile(r'^(小+卡)*[？，。！]?跳舞[？，。！]?')
]


# 跳舞54
async def dance_relu(prompt):
    dance_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["dance"]:
            if re.match(i, prompt):
                return '54'
    except:
        for i in dance_regex_relus:
            if re.match(i, prompt):
                return '54'
    return None


# 附近/位置问题正则规则
neighborhood_problem_regex_relus = [
    re.compile(r'.*(附近|身边|旁边|周围|边上)(哪里)?有.*'),
    re.compile(r'^(小卡)*[，。！？]?(当前)?位置[？，。！]?$'),
    re.compile(r'.*(小卡)*[，。！？]?我(现在|当前)(位置)?在哪[？，。！]?.*')
]


# 附近问题
async def neighborhood_problem_relu(prompt):
    neighborhood_problem_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["neighborhood_problem"]:
            if re.match(i, prompt):
                return '附近'
    except:
        for i in neighborhood_problem_regex_relus:
            if re.match(i, prompt):
                return '附近'
    return None


# 东风客服电话67
DONGFENG_service_regex_relus = [
    re.compile(r'.*东风((卡|商用)车)?(服务|客服|售后)(电话|热线).*')
]


# 东风客服67
async def dongfeng_service_relu(prompt):
    dongfeng_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["dongfeng_service"]:
            if re.match(i, prompt):
                return '67'
    except:
        for i in DONGFENG_service_regex_relus:
            if re.match(i, prompt):
                return '67'
    return None


# 陕汽客服电话68
SHANQI_service_regex_relus = [
    re.compile(r'.*陕汽((卡|商用)车)?(服务|客服|售后)(电话|热线).*')
]


# 陕汽客服68
async def shanqi_service_relu(prompt):
    shanqi_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["shanqi_service"]:
            if re.match(i, prompt):
                return '68'
    except:
        for i in SHANQI_service_regex_relus:
            if re.match(i, prompt):
                return '68'
    return None


# 中国重汽客服电话69
SINOTRUK_service_regex_relus = [
    re.compile(r'.*(中国)?重汽(卡车)?(客服|服务|售后)(电话|热线).*')
]


# 中国重汽客服69
async def sinotruk_service_relu(prompt):
    sinotruk_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["sinotruk_service"]:
            if re.match(i, prompt):
                return '69'
    except:
        for i in SINOTRUK_service_regex_relus:
            if re.match(i, prompt):
                return '69'
    return None


# 福田客服电话70
FOTON_service_regex_relus = [
    re.compile(r'.*(福田|欧曼)(卡车|戴勒姆)?(服务|客服|售后)(电话|热线).*')
]


# 福田客服70
async def foton_service_relu(prompt):
    foton_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["foton_service"]:
            if re.match(i, prompt):
                return '70'
    except:
        for i in FOTON_service_regex_relus:
            if re.match(i, prompt):
                return '70'
    return None


# 解放客服电话71
FAW_service_regex_relus = [
    re.compile(r'.*(一汽)?解放(卡车)?(服务|客服|售后)(电话|热线).*')
]


# 福田客服71
async def faw_service_relu(prompt):
    faw_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["faw_service"]:
            if re.match(i, prompt):
                return '71'
    except:
        for i in FAW_service_regex_relus:
            if re.match(i, prompt):
                return '71'
    return None


# 打开照片墙73
open_photo_wall_regex_relus = [
    re.compile(r'.*(打开|前往)照片墙.*')
]


# 打开照片墙73
async def open_photo_wall_rule(prompt):
    try:
        for i in compiled_rules["open_photo_wall"]:
            if re.match(i, prompt):
                return '73'
    except:
        for i in open_photo_wall_regex_relus:
            if re.match(i, prompt):
                return '73'
    return None


# 打开公司介绍74
open_company_profile_regex_relus = [
    re.compile(r'.*(打开|前往)公司介绍.*')
]


# 打开公司介绍74
async def open_company_profile_rule(prompt):
    try:
        for i in compiled_rules["open_company_profile"]:
            if re.match(i, prompt):
                return '74'
    except:
        for i in open_company_profile_regex_relus:
            if re.match(i, prompt):
                return '74'
    return None


# 打开品牌历史75
open_brand_history_regex_relus = [
    re.compile(r'.*(打开|前往)品牌历史.*')
]


# 打开品牌历史75
async def open_brand_history_rule(prompt):
    try:
        for i in compiled_rules["open_brand_history"]:
            if re.match(i, prompt):
                return '75'
    except:
        for i in open_brand_history_regex_relus:
            if re.match(i, prompt):
                return '75'
    return None


# 打开产品介绍76
open_product_introduction_regex_relus = [
    re.compile(r'.*(打开|前往)产品介绍.*')
]


# 打开产品介绍76
async def open_product_introduction_rule(prompt):
    try:
        for i in compiled_rules["open_product_introduction"]:
            if re.match(i, prompt):
                return '76'
    except:
        for i in open_product_introduction_regex_relus:
            if re.match(i, prompt):
                return '76'
    return None


# # 暂停播放77
# stop_playing_regex_relus = [
#     re.compile(r'.*(暂停|停止)(播放|视频).*')
# ]
#
#
# # 暂停播放77
# async def stop_playing_rule(prompt):
#     try:
#         for i in compiled_rules["stop_playing"]:
#             if re.match(i, prompt):
#                 return '77'
#     except:
#         for i in stop_playing_regex_relus:
#             if re.match(i, prompt):
#                 return '77'
#     return None
#
#
# # 开始播放78
# start_playing_regex_relus = [
#     re.compile(r'.*(开始)?播放视频.*')
# ]
#
#
# # 开始播放78
# async def start_playing_rule(prompt):
#     try:
#         for i in compiled_rules["start_playing"]:
#             if re.match(i, prompt):
#                 return '78'
#     except:
#         for i in start_playing_regex_relus:
#             if re.match(i, prompt):
#                 return '78'
#     return None
#
#
# # 关闭视频79
# close_video_regex_relus = [
#     re.compile(r'.*(关闭|退出)视频.*')
# ]
#
#
# # 关闭视频79
# async def close_video_rule(prompt):
#     try:
#         for i in compiled_rules["close_video"]:
#             if re.match(i, prompt):
#                 return '79'
#     except:
#         for i in close_video_regex_relus:
#             if re.match(i, prompt):
#                 return '79'
#     return None
#
#
# # 关闭照片墙80
# close_photo_wall_regex_relus = [
#     re.compile(r'.*(关闭|退出)照片墙.*')
# ]
#
#
# # 关闭照片墙80
# async def close_photo_wall_rule(prompt):
#     try:
#         for i in compiled_rules["close_photo_wall"]:
#             if re.match(i, prompt):
#                 return '80'
#     except:
#         for i in close_photo_wall_regex_relus:
#             if re.match(i, prompt):
#                 return '80'
#     return None
#
#
# # 关闭公司介绍81
# close_company_profile_regex_relus = [
#     re.compile(r'.*(关闭|退出)公司介绍.*')
# ]
#
#
# # 关闭公司介绍81
# async def close_company_profile_rule(prompt):
#     try:
#         for i in compiled_rules["close_company_profile"]:
#             if re.match(i, prompt):
#                 return '81'
#     except:
#         for i in close_company_profile_regex_relus:
#             if re.match(i, prompt):
#                 return '81'
#     return None
#
#
# # 关闭品牌历史82
# close_brand_history_regex_relus = [
#     re.compile(r'.*(关闭|退出)品牌历史.*')
# ]
#
#
# # 关闭品牌历史82
# async def close_brand_history_rule(prompt):
#     try:
#         for i in compiled_rules["close_brand_history"]:
#             if re.match(i, prompt):
#                 return '82'
#     except:
#         for i in close_brand_history_regex_relus:
#             if re.match(i, prompt):
#                 return '82'
#     return None
#
#
# # 关闭产品介绍83
# close_product_introduction_regex_relus = [
#     re.compile(r'.*(关闭|退出)产品介绍.*')
# ]
#
#
# # 关闭产品介绍83
# async def close_product_introduction_rule(prompt):
#     try:
#         for i in compiled_rules["close_product_introduction"]:
#             if re.match(i, prompt):
#                 return '83'
#     except:
#         for i in close_product_introduction_regex_relus:
#             if re.match(i, prompt):
#                 return '83'
#     return None
#
#
# # 关闭图片84
# close_picture_regex_relus = [
#     re.compile(r'.*(关闭|退出)图片.*')
# ]
#
#
# # 关闭图片84
# async def close_picture_rule(prompt):
#     try:
#         for i in compiled_rules["close_picture"]:
#             if re.match(i, prompt):
#                 return '84'
#     except:
#         for i in close_picture_regex_relus:
#             if re.match(i, prompt):
#                 return '84'
#     return None
#
#
# # 切换视频85
# switch_video_regex_relus = [
#     re.compile(r'.*(切换|(下|上)一?个)视频.*')
# ]
#
#
# # 切换视频85
# async def switch_video_rule(prompt):
#     try:
#         for i in compiled_rules["switch_video"]:
#             if re.match(i, prompt):
#                 return '85'
#     except:
#         for i in switch_video_regex_relus:
#             if re.match(i, prompt):
#                 return '85'
#     return None
#
#
# # 切换图片86
# switch_picture_regex_relus = [
#     re.compile(r'.*(切换|(下|上)一?张)(图片|照片).*')
# ]
#
#
# # 切换图片86
# async def switch_picture_rule(prompt):
#     try:
#         for i in compiled_rules["switch_picture"]:
#             if re.match(i, prompt):
#                 return '86'
#     except:
#         for i in switch_picture_regex_relus:
#             if re.match(i, prompt):
#                 return '86'
#     return None

# 介绍卡车87
introduce_truck_regex_relus = [
    re.compile(r'.*(介绍|推荐)(一下)?(.*)(?<!啊)(?<!吧)(?<!呢)(卡车|重卡).*'),
    re.compile(r'.*(介绍|推荐)(一下)?(.*)(?<!啊)(?<!吧)(?<!呢)')
]

# 介绍卡车87
async def introduce_truck_rule(prompt):
    introduce_truck_rule.matching_type = 'regex'
    try:
        for i in compiled_rules["introduce_truck"]:
            match = re.match(i, prompt)
            if match:
                # 提取捕获组的内容
                captured_content = match.group(3)
                # 创建一个正则表达式来匹配所有的标点符号
                punctuation_regex = re.compile(r'[^\w\s]')
                # 使用sub方法将所有的标点符号替换为空字符串
                cleaned_content = punctuation_regex.sub('', captured_content)
                return '87', cleaned_content
    except:
        for i in introduce_truck_regex_relus:
            match = re.match(i, prompt)
            if match:
                # 提取捕获组的内容
                captured_content = match.group(3)
                # 创建一个正则表达式来匹配所有的标点符号
                punctuation_regex = re.compile(r'[^\w\s]')
                # 使用sub方法将所有的标点符号替换为空字符串
                cleaned_content = punctuation_regex.sub('', captured_content)
                return '87', cleaned_content
    return None


# 意图识别
async def intent_recognition(prompt):

    result = await dance_relu(prompt)
    if result is not None:
        return result

    result = await open_photo_wall_rule(prompt)
    if result is not None:
        return result

    result = await open_company_profile_rule(prompt)
    if result is not None:
        return result

    result = await open_brand_history_rule(prompt)
    if result is not None:
        return result

    result = await open_product_introduction_rule(prompt)
    if result is not None:
        return result

    # result = await stop_playing_rule(prompt)
    # if result is not None:
    #     return result
    #
    # result = await start_playing_rule(prompt)
    # if result is not None:
    #     return result
    #
    # result = await close_video_rule(prompt)
    # if result is not None:
    #     return result
    #
    # result = await close_photo_wall_rule(prompt)
    # if result is not None:
    #     return result
    #
    # result = await close_company_profile_rule(prompt)
    # if result is not None:
    #     return result
    #
    # result = await close_brand_history_rule(prompt)
    # if result is not None:
    #     return result
    #
    # result = await close_product_introduction_rule(prompt)
    # if result is not None:
    #     return result
    #
    # result = await close_picture_rule(prompt)
    # if result is not None:
    #     return result
    #
    # result = await switch_video_rule(prompt)
    # if result is not None:
    #     return result
    #
    # result = await switch_picture_rule(prompt)
    # if result is not None:
    #     return result

    # 如果没有匹配到任何意图，则返回None
    return None
